import { createRouter, createWebHistory } from 'vue-router'
import { ElMessageBox, ElMessage } from 'element-plus'
import MainLayout from '../layouts/MainLayout.vue'
import MapView from '../user_views/MapView.vue'
import FishView from '../user_views/FishView.vue'
import FishDetail from '../user_views/FishDetail.vue'
import UserLoginView from '../user_views/UserLoginView.vue'
import Register from '../user_views/Register.vue'
import Main from '../user_views/Main.vue'
import UserCenter from '../user_views/UserCenter.vue'
import GearView from '../user_views/GearView.vue'
import GearMarket from '../user_views/gear/GearMarket.vue'
import MySelling from '../user_views/gear/MySelling.vue'
import MyBuying from '../user_views/gear/MyBuying.vue'
import ProductDetail from '../user_views/gear/ProductDetail.vue'
import FavoriteList from '../user_views/gear/FavoriteList.vue'
import OrderDetail from '../user_views/gear/OrderDetail.vue'
import CommunityView from '../user_views/CommunityView.vue'
import CommunityHome from '../user_views/community/CommunityHome.vue'
import PostDetail from '../user_views/community/PostDetail.vue'
import MyPresentation from '../user_views/community/MyPresentation.vue'
import Cart from '../user_views/gear/Cart.vue' // 新增购物车页面
import CreateOrder from '../user_views/gear/CreateOrder.vue' // 新增创建订单页面
import MySales from '../user_views/gear/MySales.vue' // 新增我的销售订单页面
import { useAuthStore } from '@/stores/authStore'

// 管理端组件
const AdminLogin = () => import('../admin_views/AdminLogin.vue')
const AdminLayout = () => import('../admin_views/layouts/AdminLayout.vue')
const Dashboard = () => import('../admin_views/Dashboard.vue')
const UserList = () => import('../admin_views/user/UserList.vue')
const UserDetail = () => import('../admin_views/user/UserDetail.vue')
const ProductList = () => import('../admin_views/product/ProductList.vue')
const AdminProductDetail = () => import('../admin_views/product/ProductDetail.vue')
const OrderList = () => import('../admin_views/order/OrderList.vue')
const PostList = () => import('../admin_views/post/PostList.vue')
const CommentList = () => import('../admin_views/comment/CommentList.vue')
const ShopStatistics = () => import('../admin_views/shop/ShopStatistics.vue')
const CommunityStatistics = () => import('../admin_views/community/CommunityStatistics.vue')
const AdminList = () => import('../admin_views/system/AdminList.vue')
const OperationLog = () => import('../admin_views/system/OperationLog.vue')
const SystemSettings = () => import('../admin_views/system/SystemSettings.vue')
const ProfileCenter = () => import('../admin_views/profile/ProfileCenter.vue')

const routes = [
  // 管理员登录
  {
    path: '/admin/login',
    name: 'AdminLogin',
    component: AdminLogin,
    meta: { requiresAuth: false, title: '管理员登录' }
  },
  // 管理端路由
  {
    path: '/admin',
    component: AdminLayout,
    redirect: '/admin/dashboard',
    meta: { requiresAdminAuth: true },
    children: [
      {
        path: 'dashboard',
        name: 'AdminDashboard',
        component: Dashboard,
        meta: { requiresAdminAuth: true, title: '数据看板' }
      },
      {
        path: 'user',
        redirect: '/admin/user/list'
      },
      {
        path: 'user/list',
        name: 'AdminUserList',
        component: UserList,
        meta: { requiresAdminAuth: true, title: '用户列表' }
      },
      {
        path: 'user/detail/:id',
        name: 'AdminUserDetail',
        component: UserDetail,
        meta: { requiresAdminAuth: true, title: '用户详情' }
      },
      {
        path: 'product/list',
        name: 'AdminProductList',
        component: ProductList,
        meta: { requiresAdminAuth: true, title: '商品列表' }
      },
      {
        path: 'product/detail/:id',
        name: 'AdminProductDetail',
        component: AdminProductDetail,
        meta: { requiresAdminAuth: true, title: '商品详情' }
      },
      {
        path: 'order/list',
        name: 'AdminOrderList',
        component: OrderList,
        meta: { requiresAdminAuth: true, title: '订单列表' }
      },
      {
        path: 'post/list',
        name: 'AdminPostList',
        component: PostList,
        meta: { requiresAdminAuth: true, title: '帖子列表' }
      },
      {
        path: 'comment/list',
        name: 'AdminCommentList',
        component: CommentList,
        meta: { requiresAdminAuth: true, title: '评论列表' }
      },
      {
        path: 'shop/statistics',
        name: 'ShopStatistics',
        component: ShopStatistics,
        meta: { requiresAdminAuth: true, title: '商城统计' }
      },
      {
        path: 'community/statistics',
        name: 'CommunityStatistics',
        component: CommunityStatistics,
        meta: { requiresAdminAuth: true, title: '社区统计' }
      },
      {
        path: 'admin/list',
        name: 'AdminList',
        component: AdminList,
        meta: { requiresAdminAuth: true, title: '管理员管理' }
      },
      {
        path: 'log/list',
        name: 'OperationLog',
        component: OperationLog,
        meta: { requiresAdminAuth: true, title: '操作日志' }
      },
      {
        path: 'system/settings',
        name: 'SystemSettings',
        component: SystemSettings,
        meta: { requiresAdminAuth: true, title: '系统设置' }
      },
      {
        path: 'profile',
        name: 'ProfileCenter',
        component: ProfileCenter,
        meta: { requiresAdminAuth: true, title: '个人中心' }
      }
    ]
  },
  // 用户端路由
  {
    path: '/userLogin',
    name: 'UserLogin',
    component: UserLoginView,
    meta: { requiresAuth: false, title: '用户登录' }
  },
  {
    path: '/register',
    name: 'Register',
    component: Register,
    meta: { requiresAuth: false, title: '用户注册' }
  },
  {
    path: '/',
    component: MainLayout,
    redirect: '/main',
    meta: { requiresAuth: false },
    children: [
      {
        path: '/main',
        name: 'Main',
        component: Main,
        meta: { requiresAuth: false }
      },
      {
        path: '/map',
        name: 'Map',
        component: MapView,
        meta: { title: '此地有鱼地图', requiresAuth: false }
      },
      {
        path: '/fish',
        name: 'Fish',
        component: FishView,
        meta: { title: '全国鱼类大全', requiresAuth: false }
      },
      {
        path: '/fish/:id',
        name: 'FishDetail',
        component: FishDetail,
        meta: { title: '鱼类详情', requiresAuth: false }
      },
      {
        path: '/user-center',
        name: 'UserCenter',
        component: UserCenter,
        meta: { title: '个人中心', requiresAuth: true }
      },
      {
        path: '/gear',
        name: 'Gear',
        component: GearView,
        redirect: { name: 'GearMarket' },
        children: [
          {
            path: 'market',
            name: 'GearMarket',
            component: GearMarket,
            meta: { title: '二手渔具基地 - 基地首页', requiresAuth: false }
          },
          {
            path: 'selling',
            name: 'MySelling',
            component: MySelling,
            meta: { title: '二手渔具基地 - 我的出售', requiresAuth: true }
          },
          {
            path: 'buying',
            name: 'MyBuying',
            component: MyBuying,
            meta: { title: '二手渔具基地 - 我的购买', requiresAuth: true }
          },
          {
            path: 'cart',
            name: 'Cart',
            component: Cart,
            meta: { title: '二手渔具基地 - 购物车', requiresAuth: true }
          },
          {
            path: 'product/:id',
            name: 'ProductDetail',
            component: ProductDetail,
            meta: { title: '二手渔具基地 - 商品详情', requiresAuth: false }
          },
          {
            path: 'favorites',
            name: 'FavoriteList',
            component: FavoriteList,
            meta: { title: '二手渔具基地 - 我的收藏', requiresAuth: true }
          },
          {
            path: 'order/:id',
            name: 'OrderDetail',
            component: OrderDetail,
            meta: { title: '二手渔具基地 - 订单详情', requiresAuth: true }
          },
          {
            path: 'create-order/:id',
            name: 'CreateOrder',
            component: CreateOrder,
            meta: { title: '二手渔具基地 - 创建订单', requiresAuth: true }
          },
          {
            path: 'sales',
            name: 'MySales',
            component: MySales,
            meta: { title: '二手渔具基地 - 我的销售订单', requiresAuth: true }
          }
        ]
      },
      {
        path: '/community',
        name: 'Community',
        component: CommunityView,
        redirect: { name: 'CommunityHome' },
        meta: { title: '空军佬的社区' },
        children: [
          {
            path: 'communityHome',
            name: 'CommunityHome',
            component: CommunityHome,
            meta: { title: '空军佬的社区 - 社区首页', requiresAuth: false }
          },
          {
            path: 'myPresentation',
            name: 'MyPresentation', 
            component: MyPresentation,
            meta: { title: '空军佬的社区 - 我的发表', requiresAuth: true }
          },
          {
            path: 'post/:id',
            name: 'PostDetail',
            component: PostDetail,
            meta: { title: '空军佬的社区 - 帖子详情', requiresAuth: false }
          }
        ]
      },
      
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫 - 身份验证
router.beforeEach((to, from, next) => {
  const auth = useAuthStore()

  // 管理端路由所需权限映射（按路由name）
  const adminRoutePerms = {
    AdminDashboard: 'dashboard:view',
    AdminUserList: 'user:list',
    AdminUserDetail: 'user:list',
    AdminProductList: 'product:list',
    AdminProductDetail: 'product:list',
    AdminOrderList: 'order:list',
    AdminPostList: 'post:list',
    AdminCommentList: 'comment:list',
    ShopStatistics: 'shop:stats',
    CommunityStatistics: 'community:stats',
    AdminList: 'admin:list',
    OperationLog: 'log:list',
    SystemSettings: 'system:settings'
  }
  // 管理端路由守卫
  if (to.path.startsWith('/admin') && to.path !== '/admin/login') {
    const isAdminLoggedIn = auth.isAdminLoggedIn
    
    if (!isAdminLoggedIn) {
      // 防止无限循环：如果已经是从登录页跳转过来的，不再重定向
      if (from.path === '/admin/login') {
        next(false) // 取消导航
        return
      }
      next({
        path: '/admin/login',
        query: { redirect: to.fullPath }
      })
      return
    }

    // 路由级权限校验（仅当定义了权限映射时）
    const requiredPerm = adminRoutePerms[to.name]
    if (requiredPerm && !auth.hasPermission(requiredPerm)) {
      ElMessage.warning('无权限访问该页面')
      next('/admin/dashboard')
      return
    }
    
    // 设置页面标题
    if (to.meta.title) {
      document.title = `${to.meta.title} - 钓鱼助手管理系统`
    } else {
      document.title = '钓鱼助手管理系统'
    }
    next()
    return
  }
  
  // 管理员登录页路由
  if (to.path === '/admin/login') {
    document.title = '管理员登录 - 钓鱼助手管理系统'
    // 不在这里做重定向，让登录页组件自己处理已登录的情况
    next()
    return
  }
  
  // 用户端路由守卫
  const isLoggedIn = auth.isUserLoggedIn
  
  // 需要登录的页面
  if (to.meta.requiresAuth && !isLoggedIn) {
    // 弹出确认对话框
    ElMessageBox.confirm(
      '此功能需要登录后才能使用，是否前往登录？',
      '需要登录',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info',
        closeOnClickModal: false
      }
    ).then(() => {
      // 用户点击确定，跳转到登录页
      next({
        path: '/userLogin',
        query: { redirect: to.fullPath }
      })
    }).catch(() => {
      // 用户点击取消，留在当前页面
      next(false)
    })
  } else {
    // 已登录用户访问登录/注册页，重定向到首页
    if (isLoggedIn && (to.path === '/userLogin' || to.path === '/register')) {
      next('/')
    } else {
      // 设置页面标题
      if (to.meta.title) {
        document.title = `${to.meta.title} - 钓鱼助手`
      } else {
        document.title = '钓鱼助手'
      }
      next()
    }
  }
})

export default router